package org.myy.learn.hot.链表.合并链表;

public class Solution {
    public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode pre = new ListNode();
        ListNode pc = pre, pa = list1, pb = list2;
        while(pa != null && pb != null){
            if(pa.val < pb.val){
                pc.next = pa;
                pa = pa.next;
            } else {
                pc.next = pb;
                pb = pb.next;
            }
            pc = pc.next;
        }
        pc.next = pb == null ? pa : pb;
        return pre.next; //新建pc的原因
    }

    /**
     * 构建
     * @param args
     * @return
     */
    public static ListNode buildNode(int[] args){
        if(args == null || args.length == 0){return null;}
        ListNode head = new ListNode(args[0]), cur = head;
        for (int i=1; i<args.length; i++){
            cur.next = new ListNode(args[i]); //指向
            cur = cur.next;                   //移动[下次指向的准备][新建cur的原因]
        }
        return head;
    }

    /**
     * 输出
     * @param head
     */
    public static void printNode(ListNode head){
        while (head != null){
            System.out.println(head.val + "->");
            head = head.next;
        }
        System.out.println("null");
    }


    public static void main(String[] args) {
        ListNode list1 = buildNode(new int[]{1,2,3});
        ListNode list2 = buildNode(new int[]{1,2,4});
        ListNode list3 = mergeTwoLists(list1, list2);
        printNode(list3);
    }
}
